package com.wy.pdf_test.service;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.LoadState;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * @author atlin
 * @description
 * @createDate 2025/7/29 11:18
 */
@Service
public class GenReportPdf {


    public File genReportPdf() {
        System.out.println("开始 ---");
        long s = System.currentTimeMillis();
        ClassPathResource resource = new ClassPathResource("templates/examReport.html");

        // 拷贝到临时文件
        File tempFile = null;
        try {
            tempFile = File.createTempFile("examReport", ".html");
            try (InputStream in = resource.getInputStream();
                 OutputStream out = new FileOutputStream(tempFile)) {
                in.transferTo(out);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        File output = null;
        // 渲染 HTML 为 PDF
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            Page page = browser.newPage();

            page.navigate(tempFile.toURI().toString());

            // 等待 JS 执行完毕（确保图表渲染完成）
            page.waitForLoadState(LoadState.NETWORKIDLE);
            page.waitForTimeout(3); // 可根据情况调整等待时间

            output = new File("output/output.pdf");
            output.getParentFile().mkdirs();

            page.pdf(new Page.PdfOptions()
                    .setPath(output.toPath())
                    .setFormat("A4")
                    .setPrintBackground(true)
            );

        }
        long e = System.currentTimeMillis();
        System.out.println("耗时：" + (e - s) + " ms");
        return output;
    }
}
